from datetime import datetime
from flask_cors import CORS
from flask import request, redirect, url_for, jsonify, session, jsonify
from passlib.hash import pbkdf2_sha256
import sys
sys.path.append("..")
from models import UserMsg
from utils import JWT

def defineAuthViews(app,db):
    # cors跨域（* 表示允许所有路由）
    CORS (app, resources=r'/*')

    # 路由拦截器
    @app.before_request
    def before():
        url = request.path  # 当前请求的URL
        passUrl = ["/","/login", "/register"]
        if url not in passUrl and not url.startswith("/static"):
            token = request.headers.get("token")
            # 验证是否有token
            if not token:
                return jsonify({ 'msg':'无权限访问！请输入token！','code':403 })
            else:
                # 验证token是否有效
                user_id = JWT.get_parse_token(request)
                if not user_id:
                    return jsonify({ 'msg':'无权限访问！token无效！','code':403 })
                else:
                    # 验证帐号是否有效
                    obj = UserMsg.query.filter_by (id=user_id,is_delete=0).first()
                    if not obj:
                        return jsonify({ 'msg':'无权限访问！当前帐号已被注销！','code':403 })
                    else:
                        pass
        else:
            pass

    @app.route('/')
    def test():
        return "成功访问flask接口"

    @app.route('/api/admin/login',methods=['POST'])
    def login():
        input = request.form
        email = input.get('email')
        password = input.get('password')
        if email == None or len(email) == 0:
            return jsonify({"msg":"邮箱不能为空","code":403})
        elif password == None or len(password) == 0:
            return jsonify({"msg":"密码不能为空","code":403})
        # 检测密码是否正确
        try:
            obj_list = UserMsg.query.filter_by (email=email).all()
            if not obj_list or len(obj_list) == 0:
                return jsonify({"msg":"登录失败！帐号不存在","code":403})
            # 检测密码的正确性
            obj = obj_list[0]
            if not pbkdf2_sha256.verify(password,obj.password):
                return jsonify({"msg":"登录失败！密码错误","code":403})
            else:
                # 根据id生成token
                token = JWT.make_JWT(obj.id)
                # 保存到数据库中
                obj1 = db.session.query(UserMsg).filter_by(id=obj.id)[0]
                obj1.token = token
                db.session.commit ()
            return jsonify ({"msg": "登录成功!","token":token, "code":200})
        except Exception as e:
            print("登录出现异常",e)
            return jsonify({"msg":"登录出现异常!请重试","code":500})

    @app.route ('/api/admin/register', methods=['POST'])
    def register():
        input = request.form
        email = input.get('email')
        username = input.get('username')
        password = input.get('password')
        if email == None or len (email) == 0:
            return jsonify ({"msg": "邮箱不能为空", "code":403})
        elif username == None or len (username) == 0:
            return jsonify ({"msg": "昵称不能为空", "code":403})
        elif password == None or len (password) == 0:
            return jsonify ({"msg": "密码不能为空", "code":403})
        # 检测密码是否正确
        try:
            obj_list = UserMsg.query.filter_by (email=email).all ()
            if obj_list and len (obj_list) > 0:
                return jsonify ({"msg": "注册失败！邮箱已经被注册", "code":403})
            # 添加数据到数据库
            data = {
                "email":email,
                "username":username,
                "password":pbkdf2_sha256.hash(password),
                "is_delete":"0",
                "register_time":datetime.now()
            }
            article = UserMsg(**data)
            db.session.add (article)
            db.session.commit ()
            return jsonify ({"msg": "注册成功!", "code":200})
        except Exception as e:
            print ("登录出现异常", e)
            return jsonify ({"msg": "注册出现异常!请重试", "code":500})


    @app.route('/api/admin/logout')
    def logout():
        # token = request.headers.get("token")
        user_id = JWT.get_parse_token(request)
        # 更新数据库的数据
        obj = db.session.query (UserMsg).filter_by (id=user_id)[0]
        obj.token = ""
        db.session.commit ()
        return jsonify ({"msg": "退出登录成功！", "code":200})


    @app.route('/api/admin/unregister')
    def unregister():
        # token = request.headers.get("token")
        user_id = JWT.get_parse_token(request)
        # 更新数据库的数据
        obj = db.session.query (UserMsg).filter_by (id=user_id)[0]
        obj.token = ""
        obj.is_delete = "1"
        obj.delete_time = datetime.now()
        db.session.commit ()
        return jsonify ({"msg": "注销帐号成功！", "code":200})